//
//  TTShopCartCommodityViewCell.m
//  TaoTuo
//
//  Created by admin on 2019/9/2.
//  Copyright © 2019 admin. All rights reserved.
//

#import "TTShopCartCommodityViewCell.h"
#import "TTShopCartSubDetailModel.h"
#import "TTUpDownButton.h"
#import <UIImageView+WebCache.h>
#import "TTSubOrAddView.h"

@interface TTShopCartCommodityViewCell ()

@property (nonatomic, strong) TTShopCartSubDetailModel *model;
@property (nonatomic, assign) BOOL hasShadow;   // 是否有阴影

@property (nonatomic, strong) UIView *bgView;       //背景
@property (nonatomic, strong) UIButton *leftBtn;
@property (nonatomic, strong) UIView *rightBgView;  // 右侧视图的背景view
@property (nonatomic, strong) UIImageView *spImageView;
@property (nonatomic, strong) UILabel *spLabel;
@property (nonatomic, strong) UILabel *titleLabel;  // 标题
@property (nonatomic, strong) UILabel *contentLabel;    // 内容
@property (nonatomic, strong) UILabel *compareLabel;    // 比加入时降价还是涨价了
@property (nonatomic, strong) TTUpDownButton *addressBtn;
@property (nonatomic, strong) UILabel *priceLabel;  // 价格
@property (nonatomic, strong) UIImageView *selloutImageView;    // 售罄或下架图片

@property (nonatomic, strong) UILabel *fsoLable;    // 法师欧同款
@property (nonatomic, strong) UILabel *xianhuoLabel;    // 现货

@property (nonatomic, strong) UILabel *productionTimeLabel;      ///生产周期
@property (nonatomic, strong) UILabel *zgLabel; ///做工
@property (nonatomic, strong) TTSubOrAddView *subAddView;   ///增减

@end

@implementation TTShopCartCommodityViewCell

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        
        self.backgroundColor = [UIColor whiteColor];
        self.selectionStyle = UITableViewCellSelectionStyleNone;
        [self setupSubviews];
        
        UILongPressGestureRecognizer *longGesture = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longGestureAction:)];
        [self.contentView addGestureRecognizer:longGesture];
        
    }
    return self;
}


- (void)longGestureAction:(UILongPressGestureRecognizer *)gesture
{
    if (gesture.state == UIGestureRecognizerStateBegan) {
        if (self.delegate && [self.delegate respondsToSelector:@selector(longGestureActionInCommodityViewCell:deleteModel:)]) {
            [self.delegate longGestureActionInCommodityViewCell:self deleteModel:self.model];
        }
    }
}

- (void)leftBtnClick:(UIButton *)sender
{
    sender.selected = !sender.selected;
    self.model.isSelect = sender.selected;
    
    [[TTLoginSingle sharedSingle].shopCartSelectBtnSubject sendNext:@(1)];
//    [[TTLoginSingle sharedSingle].shopCartSelectBtnSubject sendNext:self.model];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"chooseShop_key" object:self.model];
    
    if (self.delegate && [self.delegate respondsToSelector:@selector(clickLeftButtonInCommodityViewCell:)]) {
        [self.delegate clickLeftButtonInCommodityViewCell:self];
    }
    
}
// 是否带阴影，是否可选，来自提交订单页面吗
- (void)setDetailModel:(TTShopCartSubDetailModel *)detailModel hasShadow:(BOOL)hasShadow canSelect:(BOOL)canSelect isFromCommitOrder:(BOOL)isFromCommitOrder
{
    [self setDetailModel:detailModel hasShadow:hasShadow canSelect:canSelect];
    self.compareLabel.hidden = isFromCommitOrder;
    if (detailModel.GoodsType == 2) {
        self.subAddView.hidden = isFromCommitOrder;
        self.xianhuoLabel.hidden = !isFromCommitOrder;
        if (isFromCommitOrder && detailModel.Number > 1) {
            self.zgLabel.text = [NSString stringWithFormat:@"%@    共%d件", self.zgLabel.text, detailModel.Number];
        }
    }
}

- (void)setDetailModel:(TTShopCartSubDetailModel *)detailModel hasShadow:(BOOL)hasShadow canSelect:(BOOL)canSelect
{
    self.model = detailModel;
    self.hasShadow = hasShadow;
    
    self.leftBtn.selected = detailModel.isSelect;
    
    [self.spImageView sd_setImageWithURL:[NSURL URLWithString:detailModel.GoodsImage] placeholderImage:[UIImage imageNamed:@"f_placeholder_img"] options:SDWebImageRetryFailed];
    self.spLabel.text = detailModel.ProductText;
    self.titleLabel.text = detailModel.GoodsTitle;
    
    self.contentLabel.text = [detailModel.GoodsDescribe componentsJoinedByString:@"\n"];
    
    if (detailModel.GoodsPriceDiff == 0) {
        self.compareLabel.hidden = YES;
        self.compareLabel.text = @"";
    } else {
        self.compareLabel.hidden = NO;
        NSString *compareStr = detailModel.GoodsPriceDiff > 0 ? @"上涨" : @"下跌";
        self.compareLabel.text = [NSString stringWithFormat:@"比加入时%@%.2f元", compareStr, ABS(detailModel.GoodsPriceDiff)];
//        self.compareLabel.hidden = detailModel.GoodsPriceDiff > 0;
    }
    
    
    if (detailModel.insetMoney) {
        // 镶嵌的
        NSString *money = [NSString stringWithFormat:@"￥%@", detailModel.insetMoney];
        NSString *priceStr = [NSString stringWithFormat:@"镶嵌费%@", money];
        NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc] initWithString:priceStr];

        [attrStr addAttributes:@{NSFontAttributeName : [UIFont systemFontOfSize:15], NSForegroundColorAttributeName : UIColorHex(FF1F1F)} range:[priceStr rangeOfString:money]];
        [attrStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:11] range:[priceStr rangeOfString:@"￥"]];
        self.priceLabel.attributedText = attrStr;
        
    } else {
        
        NSString *priceTypeText = detailModel.GoodsValuationPriceTypeText ? : @"";
        NSString *cha = detailModel.PriceDiffRang ? : @"";
        cha = [cha isEqualToString:@"±0%"] ? @"" : cha;
        NSString *money = [NSString stringWithFormat:@"￥%@", detailModel.GoodsPrice];
        NSString *priceStr = [NSString stringWithFormat:@"%@%@%@", priceTypeText, money, cha];
        
        NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc] initWithString:priceStr];
        if (priceTypeText.length > 0) {
            [attrStr addAttributes:@{NSFontAttributeName : [UIFont systemFontOfSize:15], NSForegroundColorAttributeName : UIColorHex(FF1F1F)} range:[priceStr rangeOfString:money]];
            [attrStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:11] range:[priceStr rangeOfString:@"￥"]];
            self.priceLabel.attributedText = attrStr;
        } else {
            [attrStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:11] range:[priceStr rangeOfString:@"￥"]];
            self.priceLabel.textColor = UIColorHex(FF1F1F);
            self.priceLabel.font = [UIFont systemFontOfSize:15];
            self.priceLabel.attributedText = attrStr;
        }
    }
    
    
    
    
    [self.addressBtn setTitle:detailModel.LocationName forState:UIControlStateNormal];
    
    self.bgView.frame = CGRectMake(5, 5, SCREEN_WIDTH - 10, detailModel.h - 10);
    if (hasShadow) {
        self.bgView.backgroundColor = [UIColor whiteColor];
        self.bgView.layer.cornerRadius = 5;
        self.bgView.layer.shadowColor = kMainColor.CGColor;
        self.bgView.layer.shadowOffset = CGSizeZero;
        self.bgView.layer.shadowOpacity = 0.2;
//        self.bgView.layer.shadowPath = [UIBezierPath bezierPathWithRoundedRect:self.bgView.bounds cornerRadius:5].CGPath;
    } else {
        self.bgView.backgroundColor = [UIColor clearColor];
        self.bgView.layer.cornerRadius = 0;
    }
    
    self.leftBtn.hidden = !canSelect;
    
    if (canSelect) {
        [self.rightBgView mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.top.right.bottom.equalTo(self.bgView);
            make.left.equalTo(self.leftBtn.mas_right);
        }];
        
    } else {
        [self.rightBgView mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.top.right.bottom.equalTo(self.bgView);
            make.left.equalTo(self.leftBtn).mas_offset(10);
        }];
    }
    
    // 售罄或下架处理
    if (detailModel.Status.intValue == 1) {
        self.selloutImageView.hidden = YES;
        self.titleLabel.textColor = [UIColor blackColor];
        self.contentLabel.textColor = UIColorHex(333333);
        self.compareLabel.textColor = UIColorHex(FF5555);
//        self.priceLabel.textColor = UIColorHex(FF1F1F);
        self.leftBtn.enabled = YES;
    } else {
        self.selloutImageView.hidden = NO;
        NSString *sellImageName = detailModel.Status.intValue == 2 ? @"shopcartsellout" : @"xiajia";
        self.selloutImageView.image = [UIImage imageNamed:sellImageName];
        
        self.leftBtn.enabled = NO;
        self.titleLabel.textColor = UIColorHex(999999);
        self.contentLabel.textColor = UIColorHex(999999);
        self.compareLabel.textColor = UIColorHex(FF8D8D);
//        self.priceLabel.textColor = UIColorHex(FF8D8D);
    }
    
    self.fsoLable.text = detailModel.FactoryLabel;
    self.xianhuoLabel.text = detailModel.StockTypeName;
    
    self.productionTimeLabel.text = detailModel.Cycle;
    self.zgLabel.text = [NSString stringWithFormat:@"做工:%@ 颜色:%@", detailModel.ProductGradeName, detailModel.CustomizedGoldColor];
    self.subAddView.currentValue = detailModel.Number;
    self.subAddView.maxValue = detailModel.BuyNumberMax;
    self.subAddView.minValue = detailModel.BuyNumberMin;
    
    UIColor *color = detailModel.Number <= detailModel.BuyNumberMin ? UIColorHex(EFEFEF) : [UIColor whiteColor];
    self.subAddView.subLabel.layer.backgroundColor = color.CGColor;
    
    if (detailModel.GoodsType == 2) {
        //定制
        self.zgLabel.hidden = NO;
        self.subAddView.hidden = NO;
        self.productionTimeLabel.hidden = NO;
        self.fsoLable.hidden = YES;
        self.xianhuoLabel.hidden = YES;
    } else {
        //现货
        self.zgLabel.hidden = YES;
        self.subAddView.hidden = YES;
        self.productionTimeLabel.hidden = YES;
        self.fsoLable.hidden = NO;
        self.xianhuoLabel.hidden = NO;
    }
}

- (void)setupSubviews
{
    //  contentLabel的宽度：SCREEN_WIDTH - 10 - 30 * kScale - 65 * kScale - 10 * kScale - - 10 = SCREEN_WIDTH - 105 * kScale - 20;
    
    [self.bgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.mas_equalTo(5);
        make.right.bottom.mas_equalTo(-5);
    }];
    
    [self.leftBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.bottom.equalTo(self.bgView);
        make.width.mas_equalTo(30 * kScale);
    }];
    
    [self.rightBgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.right.bottom.equalTo(self.bgView);
        make.left.equalTo(self.leftBtn.mas_right);
    }];
    
    [self.spImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(8);
        make.left.equalTo(self.rightBgView);
        make.width.height.mas_equalTo(65 * kScale);
    }];
    
    [self.selloutImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.spImageView);
    }];

    [self.spLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.spImageView.mas_bottom).mas_offset(5);
        make.centerX.equalTo(self.spImageView);
    }];
    
    [self.addressBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.rightBgView);
        make.top.equalTo(self.rightBgView).mas_offset(3);
        make.height.mas_equalTo(30 * kScale);
        make.width.mas_equalTo(40 * kScale);
    }];
    
    [self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(8);
        make.left.equalTo(self.spImageView.mas_right).mas_offset(10 * kScale);
        make.right.equalTo(self.addressBtn.mas_left).mas_offset(-5);
        make.height.mas_equalTo(22);
    }];
    
    [self.contentLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.titleLabel.mas_bottom).mas_offset(4);
        make.left.equalTo(self.titleLabel);
        make.right.equalTo(self.rightBgView).mas_offset(-10);
    }];
    
    [self.priceLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.contentLabel.mas_bottom).mas_offset(5);
        make.right.equalTo(self.rightBgView).mas_offset(-5);
    }];
    
    [self.compareLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.priceLabel);
        make.left.equalTo(self.titleLabel);
    }];
    
    
    
    [self.fsoLable mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.compareLabel.mas_bottom).mas_offset(8);
        make.left.equalTo(self.titleLabel);
        make.bottom.equalTo(self.rightBgView).mas_offset(-3);
    }];

    [self.xianhuoLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.priceLabel.mas_bottom).mas_offset(8);
        make.right.equalTo(self.priceLabel);
        make.bottom.equalTo(self.fsoLable);
    }];
    
    [self.zgLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.fsoLable);
    }];
    
    [self.subAddView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.right.equalTo(self.xianhuoLabel);
        make.width.mas_equalTo(106);
        make.height.mas_equalTo(22);
    }];
    
    [self.productionTimeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.priceLabel.mas_top).mas_offset(-3);
        make.right.equalTo(self.priceLabel);
    }];
}

///增减购物车商品数量
- (void)changeBuyCount:(int)buyCount
{
    NSDictionary *dic = @{
        @"param.shoppingCartId" : self.model.Id,
        @"param.number" : @(buyCount)
    };
    @weakify(self)
    [[LLNetworkManagerTool sharedManager] postUrlString:shopCartUpdateBuyCount_api parameters:dic success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        @strongify(self)
        self.model.Number = buyCount;
        //购物车商品数量
        [TTCommonNetData getShopCartCodeInfoSuccess:^(NSArray * _Nonnull cartCodeArray, int shopCount) {} failure:^{}];
        [[TTLoginSingle sharedSingle].shopCartSelectBtnSubject sendNext:@(1)];
        
    } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nullable error) {
        
    } showLoadingInView:self.viewController.view];
}


- (UIView *)bgView
{
    if (!_bgView) {
        _bgView = [[UIView alloc] init];
        [self.contentView addSubview:_bgView];
    }
    return _bgView;
}

- (UIButton *)leftBtn
{
    if (!_leftBtn) {
        _leftBtn = [UIButton createButtonWithNormalImage:[UIImage imageNamed:@"shopcart_unsel"] selectedImage:[UIImage imageNamed:@"shopcartlist_sel"] target:self action:@selector(leftBtnClick:)];
        [_leftBtn setImage:[UIImage imageNamed:@"shopcart_unable"] forState:UIControlStateDisabled];
        _leftBtn.imageView.contentMode = UIViewContentModeCenter;
        [self.bgView addSubview:_leftBtn];
    }
    return _leftBtn;
}

- (UIView *)rightBgView
{
    if (!_rightBgView) {
        _rightBgView = [[UIView alloc] init];
        [self.bgView addSubview:_rightBgView];
    }
    return _rightBgView;
}

- (UIImageView *)spImageView
{
    if (!_spImageView) {
        _spImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@""]];
        _spImageView.contentMode = UIViewContentModeScaleAspectFit;
        _spImageView.layer.cornerRadius = 8;
        _spImageView.layer.masksToBounds = YES;
        [self.rightBgView addSubview:_spImageView];
    }
    return _spImageView;
}

- (UIImageView *)selloutImageView
{
    if (!_selloutImageView) {
        _selloutImageView = [[UIImageView alloc] init];
        _selloutImageView.contentMode = UIViewContentModeCenter;
        [self.rightBgView addSubview:_selloutImageView];
    }
    return _selloutImageView;
}

- (UILabel *)spLabel
{
    if (!_spLabel) {
        _spLabel = [UILabel labelWithTitle:@"" color:UIColorHex(999999) fontSize:10];
        [self.rightBgView addSubview:_spLabel];
    }
    return _spLabel;
}

- (UILabel *)titleLabel
{
    if (!_titleLabel) {
        _titleLabel = [UILabel labelWithTitle:@"" color:[UIColor blackColor] font:[UIFont systemFontOfSize:15]];
        [self.rightBgView addSubview:_titleLabel];
    }
    return _titleLabel;
}

- (UILabel *)contentLabel
{
    if (!_contentLabel) {
        _contentLabel = [UILabel labelWithTitle:@"" color:UIColorHex(333333) fontSize:12];
        _contentLabel.numberOfLines = 0;
        [self.rightBgView addSubview:_contentLabel];
    }
    return _contentLabel;
}

- (UILabel *)compareLabel
{
    if (!_compareLabel) {
        _compareLabel = [UILabel labelWithTitle:@" " color:UIColorHex(FF5555) fontSize:9];
        [self.rightBgView addSubview:_compareLabel];
    }
    return _compareLabel;
}

- (UILabel *)priceLabel
{
    if (!_priceLabel) {
        _priceLabel = [UILabel labelWithTitle:@"" color:UIColorHex(DEDEDE) fontSize:9];
        [self.rightBgView addSubview:_priceLabel];
    }
    return _priceLabel;
}

- (TTUpDownButton *)addressBtn
{
    if (!_addressBtn) {
        _addressBtn = [TTUpDownButton buttonWithType:UIButtonTypeCustom];
        [_addressBtn setImage:[UIImage imageNamed:@"shopcart_dizhi"] forState:UIControlStateNormal];
        _addressBtn.titleLabel.font = [UIFont systemFontOfSize:9];
        [_addressBtn setTitle:@"" forState:UIControlStateNormal];
        [_addressBtn setTitleColor:UIColorHex(DEDEDE) forState:UIControlStateNormal];
        [self.rightBgView addSubview:_addressBtn];
    }
    return _addressBtn;
}

- (UILabel *)fsoLable
{
    if (!_fsoLable) {
        _fsoLable = [UILabel labelWithTitle:@"" color:kMainColor fontSize:12];
        [self.rightBgView addSubview:_fsoLable];
    }
    return _fsoLable;
}

- (UILabel *)xianhuoLabel
{
    if (!_xianhuoLabel) {
        _xianhuoLabel = [UILabel labelWithTitle:@"" color:kMainColor fontSize:12];
        [self.rightBgView addSubview:_xianhuoLabel];
    }
    return _xianhuoLabel;
}

- (UILabel *)productionTimeLabel
{
    if (!_productionTimeLabel) {
        _productionTimeLabel = [UILabel labelWithTitle:@"" color:kMainColor fontSize:12];
        [self.rightBgView addSubview:_productionTimeLabel];
    }
    return _productionTimeLabel;
}

- (UILabel *)zgLabel
{
    if (!_zgLabel) {
        _zgLabel = [UILabel labelWithTitle:@"" color:UIColorHex(333333) fontSize:11];
        [self.rightBgView addSubview:_zgLabel];
    }
    return _zgLabel;
}

- (TTSubOrAddView *)subAddView
{
    if (!_subAddView) {
        @weakify(self)
        _subAddView = [TTSubOrAddView subAddViewWithMin:self.model.BuyNumberMin max:self.model.BuyNumberMax clickBtnBlock:^(int currentValue) {
            @strongify(self)
            [self changeBuyCount:currentValue];
        }];
        [self.rightBgView addSubview:_subAddView];
    }
    return _subAddView;
}

@end
